package org.zgr.service;

import common.dtos.ResponseResult;
import common.enums.HttpCodeEnum;
import common.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 郑国荣
 * @Date: 2024-03-27-11:57
 * @Description:
 */
@Service
public class CaptchaService {

    @Autowired
    public RedisService redisService;

    public BufferedImage getCaptcha(String token){
        // 返回的数组第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = CaptchaUtil.newBuilder()
                .setWidth(120)   //设置图片的宽度
                .setHeight(35)   //设置图片的高度
                .setSize(6)      //设置字符的个数
                .setLines(10)    //设置干扰线的条数
                .setFontSize(25) //设置字体的大小
                .setTilt(true)   //设置是否需要倾斜
                .setBackgroundColor(Color.LIGHT_GRAY) //设置验证码的背景颜色
                .build()         //构建VerifyUtil项目
                .createImage();  //生成图片
        redisService.setCacheObject("captcha:" + token, objs[0],60 * 5, TimeUnit.SECONDS);
        // 尝试十次
        redisService.setCacheObject("captcha:try:" + token, 10, 60 * 5, TimeUnit.SECONDS);
        return (BufferedImage) objs[1];
    }

    public ResponseResult checkCaptcha(String satoken, String captcha){
        if (captcha == null || captcha.equals("")){
            return new ResponseResult(HttpCodeEnum.CAPTCHA_REQUIRE);
        }
        //中获取正确验证码
        String redisCaptcha = redisService.getCacheObject("captcha:" + satoken);
        if (redisCaptcha == null){
            return new ResponseResult(HttpCodeEnum.CAPTCHA_EXPIRE);
        }
        if (captcha.equals(redisCaptcha)){
            redisService.deleteObject("captcha:" + satoken);
            return new ResponseResult(HttpCodeEnum.CAPTCHA_SUCCESS);
        }
        //redis中尝试次数减一
        Integer tryCount = redisService.getCacheObject("captcha:try:" + satoken);
        if (tryCount != null && tryCount > 0){
            redisService.setCacheObject("captcha:try:" + satoken, tryCount - 1, 60 * 5, TimeUnit.SECONDS);
            redisService.deleteObject("captcha:" + satoken);
            // todo 禁用ip一段时间
            return new ResponseResult(HttpCodeEnum.CAPTCHA_ERROR);
        } else {
            return new ResponseResult(HttpCodeEnum.CAPTCHA_TRY_LIMIT);
        }

    }

}
